// 社交分享页面逻辑
const app = getApp();

Page({
  data: {
    currentTab: 'all',
    tabs: [
      { id: 'all', name: '全部' },
      { id: 'experience', name: '经验' },
      { id: 'question', name: '问题' },
      { id: 'achievement', name: '成果' }
    ],
    shares: [],
    loading: false,
    hasMore: true,
    currentPage: 1,
    pageSize: 10
  },

  onLoad() {
    console.log('社交分享页面加载');
    this.loadShares();
  },

  onShow() {
    console.log('社交分享页面显示');
    // 页面显示时刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadShares();
    }
  },

  // 刷新数据
  refreshData() {
    this.setData({
      shares: [],
      currentPage: 1,
      hasMore: true
    });
    this.loadShares();
  },

  // 加载分享列表
  async loadShares() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });
    console.log('开始加载分享列表...');

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/miniprogram/social/get-shares`,
          method: 'GET',
          data: {
            page: this.data.currentPage,
            page_size: this.data.pageSize,
            share_type: this.data.currentTab === 'all' ? undefined : this.data.currentTab
          },
          header: {
            'Authorization': `Bearer ${app.globalData.token || ''}`
          },
          success: resolve,
          fail: reject
        });
      });

      console.log('API响应:', res);

      if (res.statusCode === 200 && res.data.success) {
        const newShares = res.data.data.shares || [];
        const currentShares = this.data.currentPage === 1 ? [] : this.data.shares;
        
        this.setData({
          shares: [...currentShares, ...newShares],
          currentPage: this.data.currentPage + 1,
          hasMore: newShares.length === this.data.pageSize
        });
        
        console.log('分享列表加载成功，数量:', newShares.length);
      } else {
        console.error('API返回错误:', res.data);
        // 即使API失败，也显示基本界面
        this.setData({
          shares: [],
          hasMore: false
        });
      }
    } catch (error) {
      console.error('加载分享失败:', error);
      // 网络错误时也显示基本界面
      this.setData({
        shares: [],
        hasMore: false
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 标签页切换
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id;
    console.log('切换标签页:', tabId);
    
    if (tabId === this.data.currentTab) return;

    this.setData({ currentTab: tabId });
    this.refreshData();
  },

  // 创建分享
  onCreateShare() {
    console.log('点击创建分享按钮');
    
    // 检查登录状态
    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: '/pages/social/create/create'
    });
  },

  // 点赞/取消点赞
  async onLike(e) {
    e.stopPropagation();
    const shareId = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    
    console.log('点击点赞，分享ID:', shareId);

    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/miniprogram/social/toggle-like`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: { share_id: shareId },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const shares = [...this.data.shares];
        const share = shares[index];
        share.is_liked = res.data.data.is_liked;
        share.like_count = res.data.data.like_count;
        
        this.setData({ shares });
        console.log('点赞操作成功');
      }
    } catch (error) {
      console.error('点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 评论
  onComment(e) {
    e.stopPropagation();
    const shareId = e.currentTarget.dataset.id;
    console.log('点击评论，分享ID:', shareId);
    
    wx.navigateTo({
      url: `/pages/social/comments/comments?id=${shareId}`
    });
  },

  // 关注/取消关注
  async onFollow(e) {
    e.stopPropagation();
    const userId = e.currentTarget.dataset.id;
    const index = e.currentTarget.dataset.index;
    
    console.log('点击关注，用户ID:', userId);

    if (!app.globalData.token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/miniprogram/social/toggle-follow`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${app.globalData.token}`
          },
          data: { target_user_id: userId },
          success: resolve,
          fail: reject
        });
      });

      if (res.statusCode === 200 && res.data.success) {
        const shares = [...this.data.shares];
        const share = shares[index];
        share.user_info = share.user_info || {};
        share.user_info.is_following = res.data.data.is_following;
        
        this.setData({ shares });
        console.log('关注操作成功');
      }
    } catch (error) {
      console.error('关注失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 用户头像点击
  onUserProfile(e) {
    e.stopPropagation();
    const userId = e.currentTarget.dataset.id;
    console.log('点击用户头像，用户ID:', userId);
    
    wx.showToast({
      title: '用户主页功能开发中',
      icon: 'none'
    });
  },

  // 分享详情
  onShareDetail(e) {
    const shareId = e.currentTarget.dataset.id;
    console.log('点击分享详情，分享ID:', shareId);
    
    wx.navigateTo({
      url: `/pages/social/comments/comments?id=${shareId}`
    });
  },

  // 预览图片
  previewImage(e) {
    e.stopPropagation();
    const url = e.currentTarget.dataset.url;
    const urls = e.currentTarget.dataset.urls;
    
    console.log('预览图片:', url);
    
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    try {
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      
      const minute = 60 * 1000;
      const hour = minute * 60;
      const day = hour * 24;
      const month = day * 30;

      if (diff < minute) {
        return '刚刚';
      } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前';
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前';
      } else if (diff < month) {
        return Math.floor(diff / day) + '天前';
      } else {
        return date.toLocaleDateString();
      }
    } catch (error) {
      console.error('时间格式化失败:', error);
      return '';
    }
  }
});
